package com.banggood.ppsprojectarch.interceptor;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * 
 * @author weihuajiang
 * @date 2017/10/17
 */

@Slf4j
@Component
public class ApiLogInterceptor implements HandlerInterceptor {

    /**
     * 请求开始时间
     */
    private ThreadLocal<Long> startTime = new ThreadLocal<>();

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws
            Exception {
        startTime.set(System.currentTimeMillis());
        log.info("URL: {}, HTTP_METHOD: {}, IP: {}", request.getRequestURL().toString(), request.getMethod(),
                getRemoteIp(request));
        if (request.getQueryString() != null) {
            log.info("PARAMETERS: {}", request.getQueryString());
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,
                           ModelAndView modelAndView) throws Exception {
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
            throws Exception {
        log.info("RESPONSE STATUS: {}, SPEND TIME: {}, {} ", response.getStatus(), System.currentTimeMillis()
                - startTime.get() + " ms", Thread.currentThread().getName());

        startTime.remove();
    }

    /**
     * 返回请求开始时间
     * @return long
     */
    public long getStartTime() {
        return this.startTime.get();
    }

    private static String getRemoteIp(HttpServletRequest request) {
        String ip = request.getHeader("X-Real-IP");
        if (StringUtils.isBlank(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip;
    }

}
